"""
AIPPT Template Service
Handles template-related operations
"""
from typing import Dict, Any, Optional, List
from src.llm.aippt_app.utils.api_client import AIPPTAPIClient
from src.llm.aippt_app.models.aippt_models import (
    TemplateListRequest,
    RandomTemplatesRequest
)


class TemplateService:
    """Service for managing PPT templates"""

    def __init__(self, client: Optional[AIPPTAPIClient] = None):
        """
        Initialize template service

        Args:
            client: AIPPTAPIClient instance, creates new if not provided
        """
        self.client = client or AIPPTAPIClient()

    def get_filter_options(self) -> Dict[str, Any]:
        """
        Get template filter options

        Returns:
            Filter options including theme colors, categories, styles, layouts
        """
        try:
            response = self.client.get_template_options()
            if response.get('code') == 0 or response.get('data'):
                return response
            else:
                raise Exception(f"Failed to get template options: {response.get('message')}")
        except Exception as e:
            print(f"Error getting template options: {str(e)}")
            raise

    def list_templates(
        self,
        current: int = 1,
        size: int = 10,
        template_type: int = 1,
        category: Optional[str] = None,
        style: Optional[str] = None,
        theme_color: Optional[str] = None,
        layout: Optional[str] = None,
        lang: str = 'zh'
    ) -> Dict[str, Any]:
        """
        List templates with filters and pagination

        Args:
            current: Current page number
            size: Page size
            template_type: Template type (1=system templates, 4=user custom templates)
            category: Filter by category
            style: Filter by style
            theme_color: Filter by theme color
            layout: Filter by layout (Note: API may not support this filter)
            lang: Language code (zh, en, etc.)

        Returns:
            Paginated template list
        """
        try:
            response = self.client.list_templates(
                current=current,
                size=size,
                lang=lang,
                template_type=template_type,
                category=category,
                style=style,
                theme_color=theme_color
            )
            return response
        except Exception as e:
            print(f"Error listing templates: {str(e)}")
            raise

    def get_random_templates(
        self,
        count: int = 5,
        lang: str = 'zh'
    ) -> List[Dict[str, Any]]:
        """
        Get random templates

        Args:
            count: Number of templates to fetch
            lang: Language code

        Returns:
            List of random templates
        """
        try:
            response = self.client.get_random_templates(count)
            if response.get('code') == 0 and response.get('data'):
                return response['data']
            else:
                raise Exception(f"Failed to get random templates: {response.get('message')}")
        except Exception as e:
            print(f"Error getting random templates: {str(e)}")
            raise

    def get_template_by_id(self, template_id: str) -> Optional[Dict[str, Any]]:
        """
        Get template details by ID
        Note: This searches through templates to find the specific one

        Args:
            template_id: Template ID

        Returns:
            Template details if found
        """
        # Since there's no direct API to get template by ID,
        # we'll need to search through the template list
        # This is a simplified implementation
        try:
            # Try to find in first page
            response = self.list_templates(current=1, size=100)
            if response.get('data') and 'records' in response['data']:
                for template in response['data']['records']:
                    if template.get('id') == template_id:
                        return template
            return None
        except Exception as e:
            print(f"Error getting template by ID: {str(e)}")
            return None
